package com.example.infowall02.controller;

import com.example.infowall02.domain.User;
import com.example.infowall02.mapper.UserMapper;
import com.example.infowall02.service.UserService;
import com.example.infowall02.utils.AliOssUtil;
import com.example.infowall02.utils.MD5Util;
import com.example.infowall02.utils.Result;
import com.example.infowall02.utils.TokenUtils;
import io.jsonwebtoken.io.IOException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    //自动装配阿里云oss工具类
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private TokenUtils tokenUtils;

    @PostMapping("/register")
    public Result registerUser(@RequestBody User user) {
        // 检查用户名是否已经存在
        if (userMapper.existsByUsername(user.getUsername())) {
            return Result.error("用户名已经存在");
        }
        int num = userService.register(user);
        if (num == 0) {
            return Result.error("注册失败");
        } else {
            user.setPassword(" ");
            return Result.success(user);
        }
    }
    @PostMapping("/login")
    public Result<User> loginUser(@RequestBody User user,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  HttpSession session) {
        // 执行登录验证
        User loggedInUser = userService.login(user.getUsername(), user.getPassword());
        if (loggedInUser != null) {
            // 登录成功，将用户信息存入 session 中
            session.setAttribute("loggedInUser", loggedInUser.getUsername());
            session.setAttribute("loggedInUserId", loggedInUser.getId());
            // 登录成功，生成长令牌并存储在 cookie 中
            String longToken = tokenUtils.generateLongToken(loggedInUser.getUsername());
            // Cookie 为键值对数据格式
            Cookie cookie_userToken = new Cookie("cookie_userToken", longToken);
            cookie_userToken.setMaxAge(3600 * 24 * 7); // 设置 Cookie 过期时间为 1 周
            // 表示当前项目下都携带这个 cookie
            cookie_userToken.setPath("/");
            // 添加到 response 中
            response.addCookie(cookie_userToken);
            // 重要信息置空
            loggedInUser.setPassword(null);
            // 登录成功
            return Result.success(loggedInUser);
        }
        return Result.error("用户名或密码错误");
    }
    @PostMapping("/logout")
    public Result<User> logout(HttpSession session, HttpServletRequest request, HttpServletResponse response){
        // 删除session里面的用户信息
        session.removeAttribute("loggedInUser");
        session.removeAttribute("loggedInUserId");
        // 删除cookie，实现退出登录
        Cookie cookie_userToken = new Cookie("cookie_userToken", "");
        // 设置cookie的持久化时间，0
        cookie_userToken.setMaxAge(0);
        // 设置为当前项目下都携带这个cookie
        cookie_userToken.setPath(request.getContextPath());
        // 向客户端发送cookie
        response.addCookie(cookie_userToken);
        return Result.success();
    }
    @GetMapping("/getUserInfo")
    public Result<User> getUserInfo(HttpSession session){
        // 从session中获取用户id
        Object userIdObj = session.getAttribute("loggedInUserId");
        Integer userId = null;
        if (userIdObj != null) {
            try {
                userId = Integer.parseInt(userIdObj.toString());
            } catch (NumberFormatException e) {
                // 处理转换异常，例如记录日志或返回错误结果
                log.error("无法将用户ID转换为整数: {}", userIdObj, e);
                return Result.error("用户ID格式错误");
            }
        }
        if (userId == null) {
            return Result.error("未找到用户ID");
        }
        // 从数据库中查询用户信息
        User user = userService.findUserById(userId);
        if(user != null){
            user.setPassword(null);
            return Result.success(user);
        }
        return Result.error("未找到正在登录的用户");
    }
    @PutMapping("/nickname/{id}")
    public Result<User> updateNickname(@RequestBody User user, @PathVariable String id) {
        // 确保使用路径中的 id
        user.setId(id);
        User updatedUser = userService.updateNickname(user.getNickname(), Integer.parseInt(id));
        if (updatedUser != null) {
            updatedUser.setPassword(null);
            return Result.success(updatedUser);
        }
        return Result.error("修改昵称失败");
    }
    @PutMapping("/password/{id}")
    public Result<User> updatePassword(String oldPassword, String newPassword,@PathVariable int id){
        User user =userService.findUserById(id);
        if(user!=null){
            if(user.getPassword().equals(MD5Util.md5(oldPassword))){
                userService.updateUserPassword(newPassword,id);
                user.setPassword(null);
                return Result.success(user);
            }
            return Result.error("原密码错误");
        }
        return Result.error("修改密码失败");
    }
    @PostMapping("/image/{id}")
    public Result<User> updateImage(@PathVariable int id,@RequestParam("image") MultipartFile file){
        User user =userService.findUserById(id);
        if(user!=null){
            //上传文件到阿里云oss
            log.info("文件上传："+file);
            try {
                //原始文件名
                String originalFilename = file.getOriginalFilename();
                //截取文件名后缀  xxx.png
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                //构造新文件名称
                String objectName = UUID.randomUUID().toString() + extension;
                //返回文件请求路径
                String filePath = aliOssUtil.upload(file.getBytes(), objectName);
                //更新用户头像
                userService.updateUserImage(filePath,id);
            } catch (IOException e) {
                log.warn("文件上传失败");
                e.printStackTrace();
            } catch (java.io.IOException e) {
                throw new RuntimeException(e);
            }
            return Result.success(userMapper.getUserById(id));
        }
        return Result.error("修改头像失败");
    }
}
